package com.fsh.auth.domain.service.impl;

import com.fsh.auth.common.enums.IsDeletedFlagEnum;
import com.fsh.auth.domain.convert.AuthPermissionBOConverter;
import com.fsh.auth.domain.entity.AuthPermissionBO;
import com.fsh.auth.domain.redis.RedisUtil;
import com.fsh.auth.domain.service.AuthPermissionDomainService;


import com.fsh.auth.infra.basic.entity.AuthPermission;
import com.fsh.auth.infra.basic.service.AuthPermissionService;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class AuthPermissionDomainServiceImpl implements AuthPermissionDomainService {

    @Resource
    private AuthPermissionService authPermissionService;

    @Resource
    private RedisUtil redisUtil; //注入redisutil 的工具类

    /**
     * 身份验证--权限前缀
     */
    private String authPermissionPrefix = "auth.permission";

    /**
     * 身份验证--角色前缀
     */
    private String authRolePrefix = "auth.role";

    @Override
    public Boolean add(AuthPermissionBO authPermissionBO) {
        AuthPermission authPermission = AuthPermissionBOConverter.INSTANCE.convertBOToEntity(authPermissionBO);
        authPermission.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

        return authPermissionService.insert(authPermission)>0;
    }

    @Override
    public Boolean update(AuthPermissionBO authPermissionBO) {
        AuthPermission authPermission = AuthPermissionBOConverter.INSTANCE.convertBOToEntity(authPermissionBO);
        int count = authPermissionService.update(authPermission);
        return count>0;
    }

    @Override
    public Boolean delete(AuthPermissionBO authPermissionBO) {
        AuthPermission authPermission = AuthPermissionBOConverter.INSTANCE.convertBOToEntity(authPermissionBO);
        authPermission.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        // TODO 删除的时候，是否应该 修改为  禁用 和 不展示？
        return authPermissionService.update(authPermission)>0;
    }

    /**
     * 获取用户的权限，从redis中查询
     */
    @Override
    public Object getPermission(String userName) {
        //构建key，获取缓存
        String permissionKey=redisUtil.buildKey(authPermissionPrefix,userName);
        String permissionValue = redisUtil.get(permissionKey);
        if(StringUtils.isBlank(permissionValue)){
            return Collections.emptyList();
        }
        //反序列化
        List<AuthPermission> permissionList = new Gson().fromJson(permissionValue, new TypeToken<List<AuthPermission>>() {
        }.getType());
        //返回权限key
        List<String> authKeyList = permissionList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());
        return authKeyList;
    }
}
